<template>
  <div class="container">
    <!-- 导航栏 -->
    <div class="sidebar">
      <a-menu v-model:openKeys="openKeys" mode="inline">
        <a-menu-item key="1" @click="changePage('projectList')"> 查看所有绿证项目 </a-menu-item>
        <a-menu-item key="3" @click="changePage('tradeList')"> 绿证交易 </a-menu-item>
      </a-menu>
    </div>

    <!-- 主界面 -->
    <div class="content">
      <!-- 页面标题 -->

      <!-- 绿证项目列表 -->
      <a-card title="绿证管理">
        <div v-if="currentPage === 'projectList'" class="content-card">
          <a-button type="primary" @click="showAddProjectModal" style="margin-bottom: 10px"> 新增绿证项目 </a-button>
          <a-table
            :columns="projectColumns"
            :dataSource="projects"
            rowKey="name"
            bordered
            @change="handleChange"
            class="carbon-assets-table"
            :pagination="pagination"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <span class="action-buttons">
                  <a @click="editProject(record)" class="edit-button">编辑</a>
                  <a-divider type="vertical" />
                  <a @click="deleteProject(record)" class="delete-button">删除</a>
                </span>
              </template>
            </template>
          </a-table>
        </div>

        <!-- 绿证交易列表 -->
        <div v-if="currentPage === 'tradeList'" class="content-card">
          <a-button type="primary" @click="showAddTradeModal" style="margin-bottom: 10px"> 新增交易 </a-button>
          <a-table :columns="tradeColumns" :dataSource="trades" rowKey="date" bordered />
        </div>
      </a-card>
    </div>

    <!-- 编辑项目的对话框 -->
    <a-modal v-model:visible="editProjectModalVisible" title="编辑项目" @ok="saveProject">
      <a-form :model="editProjectData" layout="vertical">
        <a-form-item label="项目名称">
          <a-input v-model:value="editProjectData.projectName" />
        </a-form-item>
        <a-form-item label="项目类型">
          <a-select
            v-model:value="editProjectData.assetCategoryId"
            style="width: 100%"
            :fieldNames="{ label: 'caCategoryName', value: 'caCategoryId' }"
            placeholder="选择碳资产类型"
            :options="assetsCategories"
          ></a-select>
        </a-form-item>
        <a-form-item label="绿证数量">
          <a-input v-model:value="editProjectData.greenCertificateAmount" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model:value="editProjectData.certificationStatus">
            <a-select-option value="已认证">已认证</a-select-option>
            <a-select-option value="待认证">待认证</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="详细描述">
          <a-textarea v-model:value="editProjectData.description" rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 新增项目的对话框 -->
    <a-modal v-model:visible="addProjectModalVisible" title="新增绿证项目" @ok="addProject">
      <a-form :model="newProject" layout="vertical">
        <a-form-item label="项目名称">
          <a-input v-model:value="newProject.projectName" />
        </a-form-item>
        <a-form-item label="项目类型">
          <a-select
            v-model:value="newProject.assetCategoryId"
            style="width: 100%"
            :fieldNames="{ label: 'caCategoryName', value: 'caCategoryId' }"
            placeholder="选择碳资产类型"
            :options="assetsCategories"
          ></a-select>
        </a-form-item>
        <a-form-item label="绿证数量">
          <a-input v-model:value="newProject.greenCertificateAmount" />
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model:value="newProject.certificationStatus">
            <a-select-option value="已认证">已认证</a-select-option>
            <a-select-option value="待认证">待认证</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="详细描述">
          <a-textarea v-model:value="newProject.description" rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑交易的对话框 -->
    <a-modal v-model:visible="editTradeModalVisible" title="编辑交易" @ok="saveTrade">
      <a-form :model="editTradeData" layout="vertical">
        <a-form-item label="交易日期">
          <a-date-picker v-model="editTradeData.date" />
        </a-form-item>
        <a-form-item label="类型">
          <a-input v-model="editTradeData.type" />
        </a-form-item>
        <a-form-item label="交易量">
          <a-input v-model="editTradeData.amount" />
        </a-form-item>
        <a-form-item label="交易类型">
          <a-select v-model="editTradeData.tradeType">
            <a-select-option value="买入">买入</a-select-option>
            <a-select-option value="卖出">卖出</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="详细描述">
          <a-textarea v-model="editTradeData.description" rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
  import { message } from 'ant-design-vue';
  import { h, reactive, computed, ref, onMounted } from 'vue';
  import { greenCertificate } from '/@/api/Carbon module/Carbon asset module/Carbon asset project/greenCertificate';
  import { smartSentry } from '/@/lib/smart-sentry';

  // 定义 openKeys 作为响应式属性，用于控制菜单的展开
  const openKeys = ref(['sub1']);

  // 当前页面
  const currentPage = ref('projectList');

  // 项目列表
  const projects = ref([]);

  // 绿证项目表格列
  const projectColumns = [
    { title: '项目名称', dataIndex: 'projectName', key: 'projectName' },
    { title: '类型', dataIndex: 'caCategoryName', key: 'caCategoryName' },
    { title: '绿证数量', dataIndex: 'greenCertificateAmount', key: 'greenCertificateAmount' },
    { title: '状态', dataIndex: 'certificationStatus', key: 'certificationStatus' },
    { title: '操作', key: 'action', scopedSlots: { customRender: 'action' } },
  ];

  // 新增项目的对话框控制
  const addProjectModalVisible = ref(false);

  // 新增项目的数据
  const newProject = ref({
    projectName: '',
    assetCategoryId: '',
    greenCertificateAmount: '',
    certificationStatus: '待认证',
    description: '',
  });

  // 新增项目方法
  const showAddProjectModal = () => {
    newProject.value = {
      projectName: '',
      assetCategoryId: '',
      greenCertificateAmount: '',
      certificationStatus: '',
      description: '',
    };
    addProjectModalVisible.value = true;
  };

  // 添加项目
  const addProject = async () => {
    if (newProject.value.projectName && newProject.value.assetCategoryId && newProject.value.greenCertificateAmount) {
      // 添加新项目
      try {
        await greenCertificate.Add({ ...newProject.value });
        queryData();
      } catch (error) {
        console.log(error);
      }
    } else {
      // 在此处处理表单验证失败的情况
      console.log('请填写所有必需的字段。');
    }
    addProjectModalVisible.value = false; // 关闭弹窗
  };

  // 编辑项目对话框的控制和数据
  const editProjectModalVisible = ref(false);
  const editProjectData = ref({
    projectName: '',
    assetCategoryId: '',
    greenCertificateAmount: '',
    certificationStatus: '',
    description: '',
  });

  const editProject = (key) => {
    editProjectData.value = { ...key };
    assetsCategories.value.forEach((item) => {
      if (item.caCategoryName == key.caCategoryName) {
        editProjectData.value.assetCategoryId = item.caCategoryId;
      }
    });
    console.log(editProjectData.value);
    editProjectModalVisible.value = true;
  };

  const deleteProject = async (record) => {
    try {
      await greenCertificate.Delete(record.certificateProjectId);
      queryData();
    } catch (error) {
      console.log(error);
    }
  };

  // 编辑项目方法
  const saveProject = async () => {
    if (editProjectData.value.projectName && editProjectData.value.assetCategoryId && editProjectData.value.greenCertificateAmount) {
      try {
        await greenCertificate.Update({ ...editProjectData.value });
        queryData();
      } catch (error) {
        console.log(error);
      }
    }

    editProjectModalVisible.value = false;
  };

  // 交易列表
  const trades = ref([
    {
      date: '2024-01-01',
      type: '买入',
      greenCertificateAmount: '100 张',
      tradeType: '买入',
      description: '交易描述1',
    },
  ]);

  // 交易表格列
  const tradeColumns = [
    { title: '交易日期', dataIndex: 'date', key: 'date' },
    { title: '类型', dataIndex: 'type', key: 'type' },
    { title: '交易量', dataIndex: 'amount', key: 'amount' },
    { title: '交易类型', dataIndex: 'tradeType', key: 'tradeType' },
  ];

  // 新增交易的数据
  const newTrade = ref({
    date: '',
    type: '',
    amount: '',
    tradeType: '',
    description: '',
  });

  // 新增交易方法
  const showAddTradeModal = () => {
    currentPage.value = 'addTrade'; // 切换到新增交易页面
  };

  // 编辑交易对话框的控制和数据
  const editTradeModalVisible = ref(false);
  const editTradeData = ref({
    date: '',
    type: '',
    amount: '',
    tradeType: '',
    description: '',
  });

  // 编辑交易方法
  const saveTrade = () => {
    // Save the edited trade data
    editTradeModalVisible.value = false;
  };

  // 切换页面
  const changePage = (page) => {
    currentPage.value = page;
  };

  // 查询绿证列表
  const pagination = computed(() => ({
    total: total.value,
    pageSize: queryFormState.pageSize,
    current: queryFormState.pageNum,
    showTotal: (total) => `总共${total}项`,
  }));
  const queryFormState = reactive({
    pageNum: 1,
    pageSize: 10,
  });
  const tableLoading = ref(false);
  const total = ref(0); //总数
  const queryForm = reactive({ ...queryFormState });
  async function queryData() {
    tableLoading.value = true;
    try {
      queryForm.pageNum = queryFormState.pageNum; // 确保页码同步
      queryForm.pageSize = queryFormState.pageSize;
      let queryResult = await greenCertificate.query(queryForm);
      projects.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }
  const handleChange = (pagination, filters, sorter) => {
    queryFormState.pageNum = pagination.current; // 更新当前页
    queryFormState.pageSize = pagination.pageSize; // 更新页大小
    queryData();
  };

  // 碳资产类型
  const assetsCategories = ref([]);
  async function queryAssetsCategory() {
    let queryResult = await greenCertificate.queryAssetsCategory({
      pageNum: 1,
      pageSize: 100,
    });
    assetsCategories.value = queryResult.data.list;
  }

  onMounted(() => {
    queryData();
    queryAssetsCategory();
  });
</script>

<style scoped>
  .container {
    display: table;
    width: 100%;
  }

  .sidebar {
    display: table-cell;
    width: 200px; /* 左侧菜单宽度 */
    background-color: white; /* 左侧菜单背景色 */
    height: 100%;
  }

  .content {
    display: table-cell;
    height: 100%;
    padding-left: 10px;
  }

  .page-title {
    margin-bottom: 16px;
  }

  .content-card {
    background-color: #fff; /* 右侧内容卡片背景色 */
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  }

  /* 其他样式... */
</style>
